//
//  HomeViewModel.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/15.
//

import Foundation
import Combine
import ThingSmartDeviceKit

class HomeViewModel: ObservableObject {
    @Published var newAlarm = true
    @Published var bannerItems:[HomeAPI.Banner.Data] = []
    @Published var deviceList: [ThingSmartDeviceModel] = []
    @Published var itemList: [Item] = []
    
    
   
    var userInfo: HomeAPI.UserInfo.Response? {
        didSet {
            AuthManager.shared.userInfo = userInfo
        }
    }
    var cancellables = Set<AnyCancellable>()
    
    func getUserInfo()
    {
        let uid = ThingSmartUser.sharedInstance().uid
        
        let api = HomeAPI.UserInfo(userId: uid)
        let copyApi = api.withUpdatedHeaders(["uid": uid])
        NetworkManager.shared.send(copyApi, completion: {[weak self] result in
            switch result {
                case .success(let response):
                    self?.userInfo = response.data
                self?.getBanners()
                    Logger.log(.error, message: "respons.msg:\(String(describing: response.msg)), response.code \(response.code)", tag: .login)
                case .failure(let error):
                    Logger.log(.error, message: "获取banner失败: \(error)", tag: .login)
                }
        })
    }
    
    func getBanners()
    {
        let uid = ThingSmartUser.sharedInstance().uid
        let api = HomeAPI.Banner(body: .init())
        let copyApi = api.withUpdatedHeaders(["uid": uid])
        NetworkManager.shared.send(copyApi, completion: {[weak self] result in
            switch result {
                case .success(let response):
                DispatchQueue.main.async {
                    self?.bannerItems = response.data ?? []
                }
                    Logger.log(.error, message: "respons.msg:\(String(describing: response.msg)), response.code \(response.code)", tag: .login)
                case .failure(let error):
                    Logger.log(.error, message: "获取banner失败: \(error)", tag: .login)
                }
        })
    }
    
    func requestUserInfoAndTuyaLogin()
    {
        
    }
    
    func go()
    {
        TuyaManager.shared.go(deviceModel: deviceList.first!)
    }
    
    func getHomeList()
    {
        if TuyaManager.shared.isLogin() == false {
            return
        }
        TuyaManager.shared.requestHomeList()
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    break;
                case .failure(let error):
                    print("登录失败: \(error)")
                }
            }, receiveValue: { userInfo in
                //TODO: ERROR currentHome 偶尔为空，需要修复
//                self.deviceList = TuyaManager.shared.currentHome.deviceList;
//                self.itemList =
//                self.deviceList.map { Item(model: $0) }
                print("获取homelist完成 \(userInfo)")
            })
            .store(in: &cancellables)
    }
    
    func enterAlarmView()
    {
        newAlarm = !newAlarm
    }
    
    func enterScan()
    {
        
    }
    
    func queryDevice()
    {
//ThingSmartHome.
    }
    
    deinit {
        cancellables.removeAll()
    }
    
    struct Item: Identifiable{
        let id = UUID()
        let iconUrl: String
        let name: String
        let isOnline: Bool
        
        // 初始化方法，使用 Objective-C Person 对象的数据
        init(model: ThingSmartDeviceModel) {
            self.name = model.name
            self.iconUrl = model.iconUrl
            self.isOnline = model.isOnline
        }
        init(name: String, iconUrl: String, isOnline: Bool) {
            self.name = name
            self.iconUrl = iconUrl
            self.isOnline = isOnline
        }
    }
}
